#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>                                                                   
#include <arpa/inet.h>
#include <netdb.h>    
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <pthread.h>

#define MAXLINE 200
#define RIO_BUFSIZE 8192

typedef struct{
    int rio_fd;
    int rio_cnt;
    char *rio_bufptr;
    char rio_buf[RIO_BUFSIZE];

}rio_t;

typedef struct sockaddr SA;

typedef struct{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
}tm;



void itoa (int n,char s[]);

void *thread(void *vargp);

int main(int argc,char **argv){

    int listenfd,*connfdp,port;
    int clientlen;
    struct sockaddr_in clientaddr;
    struct hostent *hp;
    char *haddrp;
    pthread_t tid;

    if(argc != 2){
    
        fprintf(stderr,"usage:%s <port>\n",argv[0]);
        exit(0);
    }

    port = atoi(argv[1]);

    listenfd = open_listenfd(port);
    
    
    while(1){
    
        clientlen = sizeof(clientaddr);

        connfdp =malloc(sizeof(int));
    
        *connfdp = accept(listenfd,(SA *)&clientaddr,&clientlen);


        hp = gethostbyaddr((const char*)&clientaddr.sin_addr.s_addr,
                sizeof(clientaddr.sin_addr.s_addr),AF_INET);

        haddrp = inet_ntoa(clientaddr.sin_addr);

        printf("server connected to %s (%s)\n",hp->h_name,haddrp);

        pthread_create(&tid,NULL,thread,connfdp);

        pthread_join(tid,NULL);
    }
}


void *thread(void *vargp){
    
    time_t lt;
    tm *local;
    char sbuf[MAXLINE];
    int cnt = 0,count = 0;
    char *fp = fopen("test.txt","wb");
    char rbuf[MAXLINE];
    int connfd = *((int*)vargp);

    free(vargp);

    pthread_detach(pthread_self());

    /*lt = time(NULL); 
    local = localtime(&lt);
    strftime(sbuf,64,"%Y-%m-%d %H:%M:%S",local);
    send(connfd,sbuf,MAXLINE,0);
    */
while(cnt = recv(connfd,rbuf,MAXLINE,0)){

        //printf("%d\n",recv(connfd,rbuf,MAXLINE,0));   
        fputs(rbuf,fp);
        bzero(rbuf,sizeof(rbuf));

        count += cnt;
        }


        //printf("传输成功!,该文件单词数共%d\n!",count);

        fclose(fp);

        itoa(count,sbuf);

        //send(connfd,sbuf,MAXLINE,0);
       
        printf("该文件单词数为%s!\n",sbuf);

    close(connfd);
    
    return NULL;
}


void itoa (int n,char s[])
{
    int i,j,sign;
    char temp[MAXLINE];

    if((sign=n)<0)//记录符号
        n=-n;//使n成为正数
    i=0;
    do{
               temp[i++]=n%10+'0';//取下一个数字
    }
    while ((n/=10)>0);//删除该数字
    if(sign<0)
        temp[i++]='-';

    for(j=0;j<i;j++){//生成的数字是逆序的，所以要逆序输出
        s[j] = temp[i-j-1];
    }
    s[i] = '\0';
} 
